const path = require('path')
const fs = require('fs-extra');

const imagesFolderPath = '../cloudFiles';

const uploadFile = (req, res) => {
  if (!req.file) {
    res.json({
      code: 500,
      msg: '文件上传失败'
    });
  } else {
    const fileName = req.file.filename.replace(/\s/g, '');
    res.json({
      code: 200,
      msg: '文件上传成功',
      img: fileName
    });
  }
};

const getFileList = (req, res) => {
  fs.readdir(path.join(__dirname, imagesFolderPath), (err, files) => {
    if (err) {
      console.log(err);
      res.json({
        code: 500,
        msg: '文件获取失败'
      });
    } else {
      const fileArray = files.map((file) => {
        return {
          name: file,
          url: `${imagesFolderPath}/${file}`
        };
      });
      res.json(fileArray);
    }
  });
}

const delFile = (req, res) => {
  console.log(req.query.name)
  fs.readdir(path.join(__dirname, imagesFolderPath), (err, files) => {
    if (err) {
      console.log(err);
      res.json({
        code: 500,
        msg: '文件删除失败'
      });
    } else {
      for (let i = 0; i < files.length; i++) {
        if (files[0].name = req.query.name) {
          const filename = req.query.name;
          const filePath = path.join(__dirname, imagesFolderPath + '/' + filename)
          console.log(filePath)
          fs.unlink(filePath, (err) => {
            if (err) {
              console.log(err);
              res.status(500).json({
                error: 'Failed to delete file'
              });
            } else {
              res.json({
                success: true,
                msg: 'File deleted successfully'
              });
            }
          });
          break;

        }
      }

    }
  });
}


const clsFile = (req, res) => {
  console.log(req.query.name)
  fs.readdir(path.join(__dirname, imagesFolderPath), (err, files) => {
    if (err) {
      console.log(err);
      res.json({
        code: 500,
        msg: '文件清空失败'
      });
    } else {
      for (let i = 0; i < files.length; i++) {
        const filePath = path.join(__dirname, imagesFolderPath + '/' + files[i])
        console.log(filePath)
        fs.unlink(filePath, (err) => {
          if (err) {
            console.log(err);
            res.status(500).json({
              error: 'Failed to delete file'
            });
          } else {
          }
        });
      }
      res.json({
        success: true,
        msg: 'File deleted successfully'
      });
    }
  });
}

module.exports = {
  uploadFile,
  getFileList,
  delFile,
  clsFile
};
